#!/usr/bin/env python
#  Copyright (c) 2010
#  The Regents of the University of Michigan
#  All Rights Reserved

#  Permission is granted to use, copy, create derivative works, and
#  redistribute this software and such derivative works for any purpose,
#  so long as the name of the University of Michigan is not used in
#  any advertising or publicity pertaining to the use or distribution
#  of this software without specific, written prior authorization. If
#  the above copyright notice or any other identification of the
#  University of Michigan is included in any copy of any portion of
#  this software, then the disclaimer below must also be included.

#  This software is provided as is, without representation or warranty
#  of any kind either express or implied, including without limitation
#  the implied warranties of merchantability, fitness for a particular
#  purpose, or noninfringement.  The Regents of the University of
#  Michigan shall not be liable for any damages, including special,
#  indirect, incidental, or consequential damages, with respect to any
#  claim arising out of or in connection with the use of the software,
#  even if it has been or is hereafter advised of the possibility of
#  such damages.

import log_parser
from pydht import vuze

import collections
import glob
import sys

def main(argv):
  maybe_dht_tracked_torrents = collections.defaultdict(int)
#  unique_keys = set()  # Eff it, let's just run this

  for log in glob.glob(argv[1]):
    log_list = log_parser.get_stores(log)
    if not log_list:
      continue
    for (key, store_time, version, value) in log_list:
#      unique_keys.add(key)
      if ((len(value) <= 5 and value.isdigit()) or
          vuze.is_peer_record(value)):
        maybe_dht_tracked_torrents[key] += 1

#  num_unique_keys = len(unique_keys)
#  del unique_keys
  probably_dht_tracked_torrents = [(k,v) for (k, v) in maybe_dht_tracked_torrents.iteritems() if v >= 5]
  at_least_100_dht_tracked = sum(1 for (k, v) in probably_dht_tracked_torrents if v >= 100)
  print 'Found %d DHT keys that are probably DHT-tracked torrents (%d maybes, %d keys)' % (len(probably_dht_tracked_torrents), len(maybe_dht_tracked_torrents), 0)#num_unique_keys))
  print 'In fact, %d keys with at least 100 peer records' % at_least_100_dht_tracked

if __name__ == '__main__':
  main(sys.argv)
